﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;        //文件、流命名空间
using System.Net;       //访问服务器命名空间
using Newtonsoft.Json;  //访问序列化命名空间

namespace Cake_Management.Models     //公共工具
{
    //自定义一个泛型类
    public class DataResult<T>
    {
        public int Code { get; set; }//保存状态码

        public string Msg { get; set; }//保存错误

        public T Data { get; set; }//保存数据

    }

    //HTTP工具类
    public class HttpHelper
    {
        //在方法级别定义T泛型，只能在方法内部使用
        /// <summary>
        /// 定义一个泛型方法返回是 DataResult<T>，参数是(地址，配置动作 get/delete )
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static DataResult<T> HttpGet<T>(string url, string method)
        {
            //1、创建一个请求
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            //2、配置请求
            request.Method = method;
            //3、从请求中获得响应
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();
            //4、从响应中获取数据（流）
            Stream stream = res.GetResponseStream();
            //5、读取流
            StreamReader sr = new StreamReader(stream);
            //6、显示(需要显示的字符串不确定保存变量)
            string data = sr.ReadToEnd();
            //7、关闭流
            sr.Close();
            stream.Close();

            //字符串反序列化对象
            //将字符串转换成<DataResult<T>泛型对象
            //返回一个DataResult<T>对象
            var result = JsonConvert.DeserializeObject<DataResult<T>>(data);
            //将对象返回
            return result;
        }

        /// <summary>
        /// 带token参数的get/delete方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static DataResult<T> HttpGet<T>(string url, string method,string token)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = method;
            //实例化响应请求的头部信息
            WebHeaderCollection headers = new WebHeaderCollection();
            //在头部信息里面添加一个授权token
            headers.Add(HttpRequestHeader.Authorization, "basic " + token);
            //将信息保存在请求头中
            request.Headers = headers;
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();
            Stream stream = res.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string data = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            var result = JsonConvert.DeserializeObject<DataResult<T>>(data);
            return result;
        }

        /// <summary>
        /// 定义一个泛型方法返回是 DataResult<T>，参数是(地址，配置动作 Post/Put ，更新或添加对象)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DataResult<T> HttpPost<T>(string url, string method, object obj)
        {
            //创建一个请求
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            //设置请求
            req.Method = method;
            //设置HTTP标头值
            req.Accept = "*/*";
            //设置内容格式
            req.ContentType = "application/json";
            //请求中获取一个请求流
            Stream ReqStream = req.GetRequestStream();
            //对象序列化字符串(object,一切皆对象)
            string json = JsonConvert.SerializeObject(obj);
            //字符串转byte[]数组
            byte[] buffer = Encoding.UTF8.GetBytes(json);
            //数据写入流
            ReqStream.Write(buffer, 0, buffer.Length);

            //请求得到响应
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            //获取响应中的流
            Stream ResStream = res.GetResponseStream();
            //读取流读取响应中的流
            StreamReader sr = new StreamReader(ResStream);
            //读取所有数据保存在变量中
            string data = sr.ReadToEnd();
            //关闭流
            sr.Close();
            ResStream.Close();
            ReqStream.Close();
            //返回一个<DataResult<T>对象(字符串反序列化对象)
            return JsonConvert.DeserializeObject<DataResult<T>>(data);
        }


        /// <summary>
        /// 带token参数的Post/Put方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="obj"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static DataResult<T> HttpPost<T>(string url, string method, object obj,string token)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = method;
            //实例化响应请求的头部信息
            WebHeaderCollection headers = new WebHeaderCollection();
            //在头部信息里面添加一个授权token
            headers.Add(HttpRequestHeader.Authorization, "basic " + token);
            //将信息保存在请求头中
            req.Headers = headers;
            req.Accept = "*/*";
            req.ContentType = "application/json";
            Stream ReqStream = req.GetRequestStream();
            string json = JsonConvert.SerializeObject(obj);
            byte[] buffer = Encoding.UTF8.GetBytes(json);
            ReqStream.Write(buffer, 0, buffer.Length);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            Stream ResStream = res.GetResponseStream();
            StreamReader sr = new StreamReader(ResStream);
            string data = sr.ReadToEnd();
            sr.Close();
            ResStream.Close();
            ReqStream.Close();
            return JsonConvert.DeserializeObject<DataResult<T>>(data);
        }
    }
}
